// pages/voiceRedPacket/index/index.js
//获取应用实例
/**红包状态 0，还没抢过，1 抢过一次，还没分享 2, 抢过一次，分享过 3抢过两次了 */
import S_request from '../../../utils/requestService.js';
import CONFIG from '../../../config.js';
import * as utils from '../../../utils/util.js';
//上传语音文件到OSS（阿里云）
const uploadImage = require('../../../utils/uploadAliyun.js');
const app = getApp()

const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

var tempFilePath;
let isEndVoice = false; //判断是开始播放还是结束播放
let authState = 0; //授权状态 0：未授权,调起授权 200：授权成功 404：拒绝授权
let voiceError = false; //判断是否录音错误
let formId = 0;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    redPackId: 0, //红包编号
    baseInfo: {},
    title: '', //渠道title
    koulingTitle: '按住说出以下口令领取红包',
    dynaStyle: 'background: linear-gradient(#8ecef4, #4289f4)',
    voiceStartTime: 0,
    isVoiceing: false, //判断玩家是否正在录音

    page: 1,
    pageSize: 10,
    hasMoreData: true,
    redPackList: [],

    options: { //录音参数
      duration: 15000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50, //指定帧大小，单位 KB
    },
    modalObj: {},
    isShowHb: false,
    isShowLogin: false,
    isShowShare: false,
    isShowState: false, //重新进入，已抢过红包，显示本轮已抢过
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.isAuthRecord();
    //初始进入
    let redPackId = options.redPackId;
    this.setData({
      redPackId: redPackId
    })
    this.getBaseRedPack(false, true);
    this.getRedPackList();

    this.dynaUpdateTitle();
    this.addAudioEvent();
  },
  addAudioEvent: function() {
    innerAudioContext.onPlay(() => {
      // console.log('开始播放')
    })
    innerAudioContext.onEnded(() => {
      // console.log('播放结束')
      isEndVoice = false;
      for (let i = 0; i < this.data.redPackList.length; i++) {
        let item = this.data.redPackList[i];
        item.voiceText = item.voiceLen;
      }
      this.setData({
        redPackList: this.data.redPackList
      })
    })
    innerAudioContext.onStop(() => {
      // console.log('停止播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
      let msg = '';
      switch (res.errCode) {
        case 10001:
          msg = '系统错误'
          break;
        case 10002:
          msg = '网络错误'
          break;
        case 10003:
          msg = '文件错误'
          break;
        case 10004:
          msg = '格式错误'
          break;
        default:
          msg = '未知错误'
          break;
      }
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
    })
  },
  getBaseRedPack: function(isShowShare, isOnLoad) {
    S_request.redPack.getBaseRedPack(this.data.redPackId, (result) => {
      let info = result.info;
      if (info.state == 1) {
        info.otherNum = info.redpack_num - info.send_num
      }
      this.setData({
        baseInfo: info
      })
      console.log("result.info==" + JSON.stringify(result.info))
      if (isOnLoad && info.state == 3) {
        this.data.modalObj.title = '本轮已经抢过，分享给好友，加速等待下一轮红包。';
        this.setData({
          modalDealIdx: 1,
          modalObj: this.data.modalObj,
          isShowShare: true,
          isShowState: true
        })
      }
      /**else {
        if (!isShowShare) return;
        if (this.data.baseInfo.state == 0 || this.data.baseInfo.state == 1) {
          this.data.modalObj.title = '分享给好友，可再抢一次红包';
          this.setData({
            modalDealIdx: 1,
            modalObj: this.data.modalObj,
            isShowShare: true
          })
        } else {
          this.setData({
            modalDealIdx: 0,
            isShowShare: false
          })
        }
      } */
    })
  },
  getRedPackList: function() {
    let self = this;
    S_request.redPack.getRedPackList(this.data.redPackId, this.data.page, (result) => {
      let redPackList = self.data.redPackList;
      if (result.page == 1) {
        redPackList = []
      } else {
        // 隐藏加载框
        wx.hideLoading();
      }
      if (result.lists.length < self.data.pageSize) {
        redPackList = redPackList.concat(result.lists);
        self.setData({
          hasMoreData: false
        })
      } else {
        redPackList = redPackList.concat(result.lists);
        self.setData({
          hasMoreData: true,
          page: self.data.page + 1
        })
      }
      for (let i = 0; i < redPackList.length; i++) {
        let list = redPackList[i];
        list.time = utils.formatTime(list.create_time, 2);
        if (list.sex != '0') {
          list.sexIcon = "../image/sex_" + list.sex + ".png";
        }
        let tempTime = parseInt(list.timeing);
        let timeing = tempTime % 1000 == 0 ? (tempTime - tempTime % 1000) / 1000 : (tempTime - tempTime % 1000) / 1000 + 1;
        list.widthNum = 130 + 10 * timeing;
        list.voiceLen = timeing + "''";
        list.voiceText = list.voiceLen;
        if (list.nickname.length >= 10) {
          list.width = 240
        }
        // list.money = list.money+'';
        // let txt = list.money.split('.')[0];
        // if (parseInt(txt) >= 1) {
        //   list.showWang = true;
        // } else {
        //   list.showWang = false;
        // }
      }
      this.setData({
        redPackList: redPackList
      })
    })
  },
  dynaUpdateTitle: function() {
    //实现渠道定制，动态修改标题名字
    let name = wx.getStorageSync("gameTitle");
    if (name == "") {
      name = '多好玩乐园'
    }
    wx.setNavigationBarTitle({
      title: name
    });
    this.setData({
      title: name
    })
  },
  //============== 红包语音 ====================
  startRecord: function(e) {
    let self = this;
    console.log("开始e.timeStamp==" + e.timeStamp)
    this.setData({
      voiceStartTime: e.timeStamp
    })
    if (authState == 0) {
      wx.authorize({
        scope: 'scope.record',
        success() {
          // 用户已经同意小程序使用录音功能, 开始录音
          authState = 200;
        },
        fail() {
          authState = 404;
        }
      })
    } else if (authState == 200) {
      this.luyinStyle();
      this.start();
    } else if (authState == 404) {
      wx.authorize({
        scope: 'scope.record',
        success() {
          // 用户已经同意小程序使用录音功能, 开始录音
          authState = 200;
          self.luyinStyle();
          self.start();
        },
        fail() {
          self.setData({
            modalDealIdx: 1,
            isShow: true
          })
        }
      })
    }
  },
  luyinStyle: function() {
    this.setData({
      koulingTitle: '松开结束录音',
      dynaStyle: 'background: linear-gradient(#7690ce, #7690ce);',
      isVoiceing: true
    })
  },
  //开始录音的时候
  start: function() {
    //开始录音
    recorderManager.start(this.data.options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    // this.errorVoiceCB();
  },
  errorVoiceCB: function() {
    if (authState != 200) return;
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
      voiceError = true;
      wx.showToast({
        title: '录音失败请重试',
        icon: 'none',
        duration: 2000
      })
      this.setData({
        koulingTitle: '按住说出以下口令领取红包',
        dynaStyle: 'background: linear-gradient(#8ecef4, #4289f4);',
        isVoiceing: false
      })
    })
  },
  stopRecord: function(e) {
    console.log("结束e.timeStamp==" + e.timeStamp)
    this.setData({
      koulingTitle: '按住说出以下口令领取红包',
      dynaStyle: 'background: linear-gradient(#8ecef4, #4289f4);',
      isVoiceing: false
    })
    this.stop(e);
  },
  //停止录音
  stop: function(e) {
    if (voiceError || authState != 200) return;
    let self = this;
    recorderManager.stop();

    //隐藏录音gif
    this.setData({
      isVoiceing: false
    })
    //判断录音时间
    let voiceStartTime = this.data.voiceStartTime;
    let voiceTimeOver = e.timeStamp;
    let timeIng = 0; //录音的时长
    timeIng = voiceTimeOver - voiceStartTime;
    console.log("voiceTimeOver==" + timeIng)
    this.stopVoiceCB(timeIng);
  },
  stopVoiceCB: function(timeIng) {
    let self = this;
    recorderManager.onStop((res) => {
      if (timeIng <= 500) {
        wx.showToast({
          title: '录音时间太短',
          icon: 'none',
          duration: 2000
        })
      } else {
        // this.tempFilePath = res.tempFilePath;
        console.log('停止录音', res.tempFilePath)
        // let fileName = res.tempFilePath.replace('.mp3', '')
        let token = wx.getStorageSync("token");
        console.log("formId----" + formId)
        wx.showLoading({
          title: '正在拼命抢',
          mask: true
        })
        uploadImage({
          filePath: res.tempFilePath,
          dir: "",
          formId: formId,
          success: function(res) {
            // console.log("res==" + JSON.stringify(res))
            let voiceurl = CONFIG.ENV.uploadVoiceUrl + "/" + res.key;
            // console.log("voiceurl==" + voiceurl)
            S_request.redPack.grabRedPackNew(self.data.redPackId, timeIng, res.formId, voiceurl, (result) => {
              setTimeout(function() {
                wx.hideLoading();
                let name = wx.getStorageSync("gameTitle");
                if (name == "") {
                  name = '多好玩乐园'
                }
                self.data.modalObj.title = name;
                self.data.modalObj.money = result.money;
                if (self.data.baseInfo.state == 0 || self.data.baseInfo.state == 1) {
                  self.data.modalObj.detail = "分享后可再抢一次红包"
                } else {
                  self.data.modalObj.detail = "看看哪个好友手气最好"
                }
                self.data.modalObj.logo = self.data.baseInfo.logo
                self.setData({
                  modalDealIdx: 1,
                  modalObj: self.data.modalObj,
                  isShowHb: true
                })
              }, 2000)
            })
          },
          fail: function(res) {
            console.log("上传失败")
            console.log(res)
          }
        })
      }
    })
  },
  testYuYin: function() {
    //第一版：语音直接上传到服务器（下面第一版）  第二版： 语音上传到阿里云OSS
    wx.uploadFile({
      url: CONFIG.grabRedPack + "?id=" + this.data.redPackId,
      filePath: res.tempFilePath,
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: {
        'token': token,
        'timeIng': timeIng,
        'formId': formId
      },
      success: (result) => {
        console.log("data===" + result.data);
        let data = JSON.parse(result.data);
        if (data.code != 0) {
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          setTimeout(function() {
            wx.hideLoading();
            let name = wx.getStorageSync("gameTitle");
            if (name == "") {
              name = '多好玩乐园'
            }
            self.data.modalObj.title = name;
            self.data.modalObj.money = data.data.money;
            if (self.data.baseInfo.state == 0 || self.data.baseInfo.state == 1) {
              self.data.modalObj.detail = "分享后可再抢一次红包"
            } else {
              self.data.modalObj.detail = "看看哪个好友手气最好"
            }
            self.setData({
              modalDealIdx: 1,
              modalObj: self.data.modalObj,
              isShowHb: true
            })
          }, 2000)
        }
      },
      fail: res => {
        console.log("fail data===" + JSON.stringify(res.data));
      }
    })
  },
  closeBtnAc: function(e) {
    this.setData({
      modalDealIdx: 0,
      isShowHb: false
    })
    this.getBaseRedPack(true);
    this.getRedPackList();
  },
  closeShareBtnAc: function(e) {
    this.setData({
      modalDealIdx: 0,
      isShowShare: false
    })
    this.getBaseRedPack();
    this.getRedPackList();
  },
  //播放声音
  playVoice: function(e) {
    let voiceUrl = e.currentTarget.dataset.url;
    let id = e.currentTarget.dataset.id;
    let selectItem;
    for (let i = 0; i < this.data.redPackList.length; i++) {
      let item = this.data.redPackList[i];
      if (id == item.id) {
        selectItem = item;
        break;
      }
    }
    innerAudioContext.src = voiceUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.startTime = 0;
    if (!isEndVoice) {
      innerAudioContext.play();
      selectItem.voiceText = "播放中..."
    } else {
      innerAudioContext.stop();
      selectItem.voiceText = selectItem.voiceLen;
    }
    this.setData({
      redPackList: this.data.redPackList
    })
    isEndVoice = !isEndVoice;
  },
  modalRightAc: function() {
    this.setData({
      modalDealIdx: 0,
      isShow: false
    });
  },
  tixian: function() {
    wx.navigateTo({
      url: '../tixian/tixian?redPackId=' + this.data.redPackId,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.isAuthUserinfo(); //用户信息是否授权
    if (this.data.redPackId != 0 && this.data.page != 1) {
      this.getBaseRedPack();
      this.getRedPackList();
    }
    if (this.data.baseInfo.state == 1) { // 抢过一次，还没分享
      this.getBaseRedPack(true);
      this.getRedPackList();
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // innerAudioContext.destroy();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log("正在刷新数据")
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.hasMoreData) {
      wx.showLoading({
        title: '玩命加载中',
        mask: true
      })
      this.getRedPackList();
    } else {
      if (this.data.page != 1) {
        wx.showToast({
          title: '没有更多数据',
        })
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    // console.log("sharePath====" + CONFIG.SHARE.pathVoice)
    wx.showShareMenu({
      withShareTicket: true,
      success: function() {}
    });
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    let sharePath = CONFIG.SHARE.pathVoice + "&redPackId=" + this.data.redPackId;
    let obj = { 'pagepath': sharePath, "redPackId": this.data.redPackId,'sign':1}
    S_request.index.recordShare("-5", obj);
    console.log("sharePath====" + sharePath)
    return {
      title: CONFIG.SHARE.titleVoice,
      path: sharePath,
      imageUrl: CONFIG.SHARE.imagVoiceUrl,
      success: res => { //新版不走回调
        console.log("分享成功")
      }
    }
  },
  isAuthUserinfo: function() {
    let self = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.userInfo'] == true) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          app.globalData.isAuthorize = true;
          this.getUserInfo();
          this.modalLoginRightAc();
          this.isAuthRecord(); //录音是否授权
        } else if (authSetting['scope.userInfo'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          app.globalData.isAuthorize = false;
          this.showLoginModal();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          app.globalData.isAuthorize = false;
          this.showLoginModal();
        }
      }
    })
  },
  isAuthRecord: function() {
    wx.getSetting({
      success: (res) => {
        //录音功能已授权
        // console.log("sdvdfdb===" + res.authSetting.hasOwnProperty("scope.record"))
        if (!res.authSetting.hasOwnProperty("scope.record")) {
          console.log('第一次操作')
          authState = 0;
        } else if (res.authSetting["scope.record"]) {
          console.log('授权成功')
          authState = 200;
          this.modalRightAc();
        } else {
          authState = 404;
        }
      }
    })
  },
  getUserInfo: function() {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        this.setData({
          userinfo: app.globalData.userInfo,
        });
        S_request.index.updateUserInfo(res.userInfo, (result) => {
          console.log("更新与用户信息成功====" + JSON.stringify(result));
          app.globalData.goldnum = result.goldcoin;
        })
      }
    })
  },
  showLoginModal: function() {
    this.setData({
      modalDealIdx: 1,
      isShowLogin: true
    })
  },
  modalLoginRightAc: function() {
    this.setData({
      modalDealIdx: 0,
      isShowLogin: false
    })
  },
  playGame: function(e) {
    let id = e.currentTarget.dataset.id;
    let param = 'formId=0'
    S_request.index.tongJiNum(id, param, (result) => {
    })
  },
  openWB:function(e) {
    let id = e.currentTarget.dataset.id;
    let apid = e.currentTarget.dataset.apid;
    if (apid == 'no') return;
    let path = encodeURIComponent(e.currentTarget.dataset.path);
    wx.navigateTo({
      url: '../webv/webv?url=' + path,
    })
    console.log("path====" + path)
    let param = 'formId=0'
    S_request.index.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
  },
  formSubmit: function(e) {
    formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)

    // if (e.detail.formId != 'the formId is a mock one') {
    //   this.setData({
    //     formIdString: e.detail.formId + "," + this.data.formIdString
    //   })
    // }
    // console.log(this.data.formIdString)
  }
})